package jp.sourceforge.akjrcp.psp.imageconvert;

import java.awt.Graphics2D;
import java.awt.geom.AffineTransform;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;

import javax.imageio.ImageIO;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;

import jp.sourceforge.akjrcp.util.image.ImageUtils;

public class ImageResizer extends AbstractImageChanger{
	public static Log log=LogFactory.getLog(ImageResizer.class);
	public static final int TURN_RIGHT=0;
	
	public ImageResizer(){
		time=System.currentTimeMillis();
	}
	
	public void changeImage(String imageFileName,InputStream imageInput,File exportDir) throws IOException{
		if(cancel){
			return;
		}
		BufferedImage baseImage=imageLoader.loadImage(imageFileName,imageInput);
		BufferedImage argb=toARGB(baseImage);
		//saveImage(argb,0,"argb_"+imageFileName,exportDir);//for debug
		baseImage.getGraphics().dispose();//for keep memory
		
		int resizeW=width;
		int resizeH=height;
		
		if(width==0 && height==0){
			log.warn("set width or height");
			return;
		}else if(width==0){//fit height
			double ratio=(double)baseImage.getHeight()/height;
			resizeW=(int) (baseImage.getWidth()/ratio);
			resizeH=height;
		}else if(height==0){
			double ratio=(double)baseImage.getWidth()/width;
			resizeH=(int) (baseImage.getHeight()/ratio);
			resizeW=width;
		}
		log.trace("resize:"+resizeW+"x"+resizeH);
		BufferedImage fit=ImageUtils.fitImage(argb,resizeW,resizeH);
		//saveImage(argb,0,"fit_"+imageFileName,exportDir);//for debug
		argb.getGraphics().dispose();
		
		BufferedImage rgb=toRGB(fit);
		fit.getGraphics().dispose();
		
		saveImage(rgb,imageFileName,exportDir);
		rgb.getGraphics().dispose();
		System.gc();
	}
	

}
